<template>
  <div class="member-container">
    <!-- 顶部选项卡 -->
    <el-tabs v-model="activeTab">
      <el-tab-pane label="成员管理" name="members"></el-tab-pane>
      <el-tab-pane label="待审核" name="pending">
        <template #label>
          <span>待审核 <el-badge v-if="pendingCount > 0" :value="pendingCount" class="badge"/></span>
        </template>
      </el-tab-pane>
    </el-tabs>

    <!-- 成员管理 -->
    <div v-if="activeTab === 'members'">
      <div class="toolbar">
        <el-button-group>
          <el-button type="primary" icon="el-icon-plus" @click="showInviteDialog">邀请成员</el-button>
          <el-button icon="el-icon-s-operation" @click="showSubGroupDialog">分组管理</el-button>
          <el-button icon="el-icon-key" @click="showInviteManage">邀请码管理</el-button>
        </el-button-group>
      </div>
      <!-- 成员列表     -->
      <el-table :data="members" style="width: 100%">
        <el-table-column prop="userName" label="姓名" width="180">
          <template slot-scope="scope">
            <div class="user-info">
              <el-avatar :size="30" :src="scope.row.avatar"></el-avatar>
              <span style="margin-left: 10px;">{{ scope.row.userName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" width="120">
          <template slot-scope="scope">
            <el-tag :type="scope.row.role === 1 ? 'danger' : scope.row.role === 2 ? 'warning' : ''">
              {{ formatRole(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="joinTime" label="加入时间"></el-table-column>
        <el-table-column prop="subgroupIds" label="所属分组">
          <template slot-scope="scope">
            {{ formatGroups(scope.row.subgroupIds) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleRemove(scope.row)"
              :disabled="scope.row.role === 1">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>


    <!-- 待审核列表 -->
    <div v-else class="pending-container">
      <el-table :data="pendingMembers" style="width: 100%">
        <el-table-column prop="userName" label="申请人" width="180">
          <template #default="{row}">
            <div class="user-info">
              <el-avatar :size="30" :src="row.avatar"></el-avatar>
              <span>{{ row.userName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="applyTime" label="申请时间"></el-table-column>
        <el-table-column prop="inviteCode" label="邀请码"></el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{row}">
            <el-button type="success" size="mini" @click="handleApprove(row, true)">通过</el-button>
            <el-button type="danger" size="mini" @click="handleApprove(row, false)">拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <sub-group-manage-dialog
      ref="groupManage"
      :groupId="groupId"
      :members="members"
    />

    <!-- 邀请成员对话框 -->
    <el-dialog title="邀请成员" :visible.sync="inviteDialogVisible" width="500px">
      <el-form :model="inviteForm" :rules="inviteRules" label-width="80px">
        <el-form-item label="用户账号" prop="userAccount">
          <el-input v-model="inviteForm.userAccount" placeholder="输入用户名/邮箱/手机号"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="inviteForm.role">
            <el-radio :label="2">次要负责人</el-radio>
            <el-radio :label="3">考生</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="需要确认">
          <el-switch v-model="inviteForm.needConfirm"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="inviteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitInvite">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加邀请码管理对话框 -->
    <el-dialog title="邀请码管理" :visible.sync="inviteManageVisible" width="80%">
      <invite-manage :groupId="groupId" ref="inviteManage"/>
    </el-dialog>
  </div>
</template>

<script>
import {
  getPendingMembers,
  approveMember,
  inviteMember,
  removeMember,
} from '@/api/exam/member'
import { getGroupDetail } from '@/api/exam/group'
import InviteManage from './InviteManage'
import SubGroupManageDialog from './SubGroupManageDialog.vue'
export default {

  props: {
    members: Array,
    groupId: [Number, String]
  },
  components: { InviteManage, SubGroupManageDialog },
  data() {
    return {
      inviteManageVisible: false,
      activeTab: 'members',
      pendingMembers: [],
      pendingCount: 0,
      inviteDialogVisible: false,
      inviteForm: {
        userAccount: '',
        role: 3,
        needConfirm: true
      },
      inviteRules: {
        userAccount: [
          { required: true, message: '请输入用户账号', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    activeTab(val) {
      if (val === 'pending') {
        this.loadPendingMembers()
      }
    }
  },
  methods: {
    showSubGroupDialog() {
      this.$refs.groupManage.showGroupDialog()
    },
    formatRole(role) {
      return ['', '主要负责人', '次要负责人', '考生'][role] || ''
    },
    formatGroups(ids) {
      return ids ? ids.split(',').length + '个分组' : '未分组'
    },
    showInviteManage() {
      this.inviteManageVisible = true;
      // 确保对话框完全打开后再加载数据
      this.$nextTick(() => {
        this.$refs.inviteManage?.getList();
      });
    },
    async loadPendingMembers() {
      const res = await getPendingMembers(Number(this.groupId))
      this.pendingMembers = res.rows
      this.pendingCount = res.total
    },

    showInviteDialog() {
      this.inviteDialogVisible = true
      this.$nextTick(() => {
        this.$refs.inviteForm?.clearValidate()
      })
    },

    async submitInvite() {
      try {
        await this.$refs.inviteForm.validate()
        await inviteMember({
          groupId: Number(this.groupId),
          ...this.inviteForm
        })
        this.$message.success('邀请已发送')
        this.inviteDialogVisible = false
      } catch (error) {
        console.error(error)
      }
    },

    async handleApprove(row, approved) {
      try {
        await approveMember({
          groupId: Number(this.groupId),
          memberId: row.id,
          approved,
          remark: approved ? '审核通过' : '审核拒绝'
        })
        this.$message.success(approved ? '已通过申请' : '已拒绝申请')
        await this.loadPendingMembers()
        await getGroupDetail(this.groupId).then(response => {
          this.members = response.data.members
        })
      } catch (error) {
        this.$message.error(error.message)
      }
    },

    async handleRemove(memberId) {
      try {
        await this.$confirm('确定要移除该成员吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await removeMember(memberId)
        this.$message.success('移除成功')
        this.$emit('refresh')
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message)
        }
      }
    }
  }
}
</script>

<style scoped>
.pending-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.user-info {
  display: flex;
  align-items: center;
}

.badge {
  margin-left: 5px;
}

.toolbar {
  margin-bottom: 20px;
}
</style>
